package com.mgy.im.standard;


import com.mgy.im.autoconfigure.NettyWebSocketProperties;
import com.mgy.im.constants.Constant;
import com.mgy.im.pojo.Session;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * xxx
 *
 * @author maguoyong
 * @date 2020/6/14
 */
@Slf4j
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private NettyWebSocketProperties properties;
    private WebSocketHandler webSocketHandler;


    public TextWebSocketFrameHandler(NettyWebSocketProperties properties, WebSocketHandler webSocketHandler) {
        this.properties = properties;
        this.webSocketHandler = webSocketHandler;

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("触发事件", evt);

        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            ctx.pipeline().remove(ctx.name());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        Session session = ctx.channel().attr(Constant.SESSION_KEY).get();
        webSocketHandler.handleMessage(session, msg.text());
    }

    /**
     * 不活跃，关闭连接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("Current channel channelInactive");
        ctx.close();
        Session session = ctx.channel().attr(Constant.SESSION_KEY).get();
        webSocketHandler.afterConnectionClosed(session,"通道不活跃");
    }

    /**
     * 关闭连接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("Current channel handlerRemoved");
        ctx.close();
        Session session = ctx.channel().attr(Constant.SESSION_KEY).get();
        webSocketHandler.afterConnectionClosed(session,"处理器删除");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("异常关闭连接", cause.getMessage());
        ctx.close();
        Session session = ctx.channel().attr(Constant.SESSION_KEY).get();
        webSocketHandler.handleError(session,cause);
    }
}
